<?php
namespace addons\caipiao\controller;

use addons\caipiao\service\CplistService;
use app\common\controller\Addon;
use think\App;
use think\facade\Cache;
use think\facade\Request;

/**
 * Class Api
 * @package addons\caipiao\controller
 */
class Api extends Addon {
    private $token = 'zhangzheng521';
    private $cplistS;
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->cplistS = new CplistService();
    }

    public function index(){
        $offset = input('offset',0);
        $r = $this->cplistS->getFirstTask($offset);
        $img_url = '';
        $cpid = 0;
        if($r){
            $img_url = $r['img_url'];
            $cpid = $r['id'];
            $this->cplistS->recordScan($cpid);
        }
        Cache::set('cpid',$cpid);
        $this->assign('img_url',$img_url);
        $this->assign('cpid',$cpid);
        $this->assign('offset',$offset);
        $this->assign('curl',addonUrl('caipiao/Api/index'));
        return $this->fetch();
    }

    public function task(){
        if(Request::instance()->isPost()){
            $token = Request::put('token');
            $data=[
                'ret'=>Request::put('ret'),
                'msg'=>Request::put('msg'),
                //彩票中奖金额（余额）
                'balance'=>Request::put('prize'),
                'level'=>Request::put('level')
            ];
            if(Cache::has('cpid')){
                $cpid = Cache::pull('cpid');
                if($token==$this->token){
                    $addonInfo = getAddonInfo();
                    $autoCash = $addonInfo['mp_config']['autoCash'];
                    $autoC = $autoCash == 1;
                    if($this->cplistS->scanUpdate($cpid,$data['ret'],$data['balance'],$autoC)){
                        return json(['code'=>0,'msg'=>$data['msg'],'data'=>[]]);
                    }else{
                        return json(['code'=>1,'msg'=>'请求失败,数据更新失败','data'=>[]]);
                    }
                }else{
                    return json(['code'=>1,'msg'=>'请求失败,token错误','data'=>[]]);
                }
            }else{
                return json(['code'=>1,'msg'=>'请求失败,cpid不存在','data'=>$data]);
            }
        }else{
            return json(['code'=>1,'msg'=>'请求失败','data'=>[]]);
        }
    }

    public function getid(){
        if(Cache::has('cpid')){
            $cpid = Cache::get('cpid');
            return json(['code'=>0,'msg'=>'获取成功','data'=>['cpid'=>$cpid]]);
        }else{
            return json(['code'=>1,'msg'=>'获取失败','data'=>[]]);
        }
    }
}
